<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Vote_model extends MY_Model {
    
    protected $TB_VOTE = 'dc_vote';
    protected $TB_WB_USER = 'dc_user';
    protected $VOTE_COLS = array(
        'vote_id',
        'user_id',
		'product_id',
        'vote_create_time'
    );
    
    public function __construct() {
        parent::__construct();
    }

    public function add_vote($user_id, $product_id, $vote_create_time=null) {
        $vote_create_time = $vote_create_time or date('Y-m-d H:i:s', time());
        $query = $this->db->query("INSERT INTO $this->TB_VOTE "
            ."(`user_id`, `product_id`, `vote_create_time`) VALUES"
            ."('$user_id', '$product_id', '$vote_create_time')");
        return $query ? $this->db->insert_id() : false;
    }

    public function has_vote($user_id, $product_id){
        $query = $this->db->query(
            "SELECT `vote_id` FROM $this->TB_VOTE WHERE `user_id` = $user_id "
            ."AND `product_id` = $product_id  LIMIT 1");
        return $query->num_rows() ? true : false;
    }
    
    public function del_vote($vote_id) {
        return $this->db->query("DELETE FROM $this->TB_VOTE "
            ."WHERE `vote_id` = $vote_id LIMIT 1");
    }
    
    public function set_vote($vote_id, $sets) {
        $sets_sql = $this->_sets_to_str($sets, $this->PRODUCT_COLS);
        return $this->db->query("UPDATE $this->TB_VOTE SET $sets_sql "
            ."WHERE `vote_id` = $vote_id LIMIT 1");
    }

    public function get_sum_production_vote($product_id){
        $query = $this->db->query("SELECT `vote_id` FROM $this->TB_VOTE "
            ."WHERE `product_id` = $product_id");
        return $query->num_rows();
    }
    
    public function get_product_votes_list(
        $product_id, $cols=null, $start_index, $step) {
        $start_index--;
        $cols_str = $cols ? join(',', $cols) : join(',', $this->VOTE_COLS);
        return $this->db->query(
            "SELECT `user_wb_screen_name`, `vote_create_time` FROM "
            ."$this->TB_VOTE V, $this->TB_WB_USER U WHERE V.`user_id` = "
            ."U.`user_id` and `product_id` = $product_id ORDER BY `vote_id` "
            ."desc LIMIT $start_index, $step")->result();
    }

}